package it.apiconsulting.wot.controller;


import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;

import it.apiconsulting.wot.model.FoodCategory;
import it.apiconsulting.wot.util.HibernateUtil;


public class FoodCategoryManager extends HibernateUtil {
	
	public FoodCategory add(FoodCategory foodCategory) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(foodCategory);
		session.getTransaction().commit();
		return foodCategory;
	}
	public FoodCategory delete(Long id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		FoodCategory foodCategory = (FoodCategory) session.load(FoodCategory.class, id);
		if(null != foodCategory) {
			session.delete(foodCategory);
		}
		session.getTransaction().commit();
		return foodCategory;
	}
	
	public FoodCategory getFoodCategoryById(Long idCategory) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		FoodCategory foodCategory = null;
		try {
			
			Query query = session.createQuery("FROM FoodCategory WHERE id = "+idCategory);
			foodCategory = (FoodCategory)query.uniqueResult();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return foodCategory;
	}

	public List<FoodCategory> list() {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<FoodCategory> foodCategories = null;
		try {
			
			Query query = session.createQuery("from FoodCategory");
			foodCategories = (List<FoodCategory>)query.list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return foodCategories;
	}
}
